﻿using BootstrapBlazor.Components;
using BPM.Web.Shared.Data;

namespace BPM.Web.Shared.Extensions;

/// <summary>
/// MenuItem组件扩展
/// </summary>
public static class MenuItemExtensions
{
    /// <summary>
    /// ITreeNode集合数据转换为MenuItem
    /// </summary>
    /// <typeparam name="TKey">标识类型</typeparam>
    /// <param name="items"></param>
    /// <returns></returns>
    public static List<MenuItem> BuildMenuItem<Tsource, Tkey>(this IEnumerable<Tsource>? items, Action<Tsource, MenuItem> action)
        where Tsource : class, ITreeNode<Tsource, Tkey>
        where Tkey : struct
    {
        if (items == null)
        {
            return new();
        }

        var result = new List<MenuItem>();
        foreach (var item in items)
        {
            var node = new MenuItem();
            action(item, node);
            if (item.Children.Any())
            {
                node.Items = BuildMenuItem<Tsource, Tkey>(item.Children, action);
            }
            result.Add(node);
        }
        return result;
    }

    /// <summary>
    /// 集合数据转换为MenuItem
    /// </summary>
    /// <typeparam name="TKey">标识类型</typeparam>
    /// <param name="items"></param>
    /// <returns></returns>
    public static List<MenuItem> BuildNodeItem<Tsource>(this IEnumerable<Tsource>? items, Action<Tsource, MenuItem> action)
        where Tsource : class
    {
        if (items == null)
        {
            return new();
        }

        var result = new List<MenuItem>();
        foreach (var item in items)
        {
            var node = new MenuItem();
            action(item, node);
            result.Add(node);
        }
        return result;
    }
}
